package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.LiveBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/11.
 */

public class AddLiveActivity extends BaseActivity implements View.OnClickListener {

    private ImageView btLeft;
    private TextView tvTitle;
    private SimpleDraweeView btCover;
    private EditText etTitle;
    private Button btSubmit;
    private TextView tvNum;

    private int id;
    private String title;
    private String image;//默认图片地址
    private String thumb;
    private String type;

    private LigDialog ligDialog;

    private static final int REQUEST_COVER = 2001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addlive);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        id = getIntent().getIntExtra("id", 0);
        initView();
    }

    private void initView() {
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        btCover = getView(R.id.bt_cover);
        etTitle = getView(R.id.et_title);
        btSubmit = getView(R.id.bt_submit);
        tvNum = getView(R.id.tv_num);
        btLeft.setOnClickListener(this);
        btCover.setOnClickListener(this);
        btSubmit.setOnClickListener(this);
        tvTitle.setText(getString(R.string.live_add));
        if (id != 0) {
            title = getIntent().getStringExtra("title");
            image = getIntent().getStringExtra("litpic");
            thumb = "";
            type = "default";
            tvTitle.setText(getString(R.string.live_title_edit));
            etTitle.setText(title);
            btSubmit.setText(getString(R.string.ensure));
            btCover.setImageURI(Uri.parse(image));
        }

        tvNum.setText(String.format(getString(R.string.live_title_num), "" + (20 - etTitle.length())));

        etTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int num = 20 - s.length();
                tvNum.setText(String.format(getString(R.string.live_title_num), "" + num));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void toSubmit() {
        title = String.valueOf(etTitle.getText());
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(AddLiveActivity.this, R.string.live_title_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(type)) { //拍照或者从相册选择
            if (TextUtils.isEmpty(thumb)) {
                Toast.makeText(AddLiveActivity.this, R.string.live_thumb_empty, Toast.LENGTH_SHORT).show();
                return;
            }

        } else { //选择默认图片
            if (TextUtils.isEmpty(image)) {
                Toast.makeText(AddLiveActivity.this, R.string.live_thumb_empty, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (title.length() > 20) {
            Toast.makeText(AddLiveActivity.this, R.string.live_title_num_more, Toast.LENGTH_SHORT).show();
            return;
        }
        if (id == 0) {
            addLive();
        } else {
            editLive();
        }
    }

    private void addLive() {
        String url = Api.URL_LIVE;
        File file = new File(thumb);
        OkHttpUtils
                .post()
                .url(url)
                .addParams("title", title)
                .addParams("image", image)
                .addParams("type", type)
                .addFile("filedata", file.getName(), file)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(AddLiveActivity.this, getString(R.string.waiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(AddLiveActivity.this, R.string.live_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        LiveBean result = JSONUtils.requestDetail(response, "data", LiveBean.class);
                        if (result != null) {
                            Toast.makeText(AddLiveActivity.this, R.string.live_add_success, Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(AddLiveActivity.this, LiveActivity.class);
                            intent.putExtra("id", result.getId());
                            intent.putExtra("userid", result.getUid());
                            intent.putExtra("title", result.getTitle());
                            intent.putExtra("album", result.getLitpic());
                            startActivity(intent);
                            setResult(Activity.RESULT_OK);
                            finish();
                        } else {
                            Toast.makeText(AddLiveActivity.this, R.string.live_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void editLive() {
        String url = Api.URL_LIVE_EDIT;
        File file = new File(thumb);
        OkHttpUtils
                .post()
                .url(url)
                .addParams("id", "" + id)
                .addParams("title", title)
                .addParams("image", image)
                .addFile("filedata", file.getName(), file)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(AddLiveActivity.this, getString(R.string.waiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(AddLiveActivity.this, R.string.live_edit_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        LiveBean result = JSONUtils.requestDetail(response, "data", LiveBean.class);
                        if (result != null) {
                            Toast.makeText(AddLiveActivity.this, R.string.live_edit_success, Toast.LENGTH_SHORT).show();
                            setResult(Activity.RESULT_OK);
                            finish();
                        } else {
                            Toast.makeText(AddLiveActivity.this, R.string.live_edit_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_left:
                finish();
                break;
            case R.id.bt_cover:
                startActivityForResult(new Intent(this, LiveCoverActivity.class), REQUEST_COVER);
                break;
            case R.id.bt_submit:
                toSubmit();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_COVER:
                image = thumb = type = "";
                String thumbTitle = data.getStringExtra("title");
                if (TextUtils.isEmpty(thumbTitle)) {
                    thumb = data.getStringExtra("thumb");
                    btCover.setImageURI(Uri.parse("file://" + thumb));
                } else {
                    image = data.getStringExtra("thumb");
                    type = thumbTitle;
                    btCover.setImageURI(Uri.parse(image));
                }
                break;
            default:
                break;
        }
    }
}
